package com.demo.webapp.kcfinder.result;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.demo.webapp.kcfinder.action.Action;
import com.demo.webapp.kcfinder.config.ResultConfig;
import com.demo.webapp.kcfinder.context.ActionContext;
import com.demo.webapp.kcfinder.model.DownloadInfo;

/**
 * 数据流结果渲染对象
 * 该对象取得Action的结果数据,以数据流形式进行渲染
 * @author ryuu.kk
 *
 */
public class ActionStreamResult implements Result {

	/**
	 * 下载文件时一次读取的字节数
	 */
	private static final int BUFFER_SIZE = 1024;
	
	@Override
	public String render(ActionContext context, ResultConfig config) throws IOException, ServletException {
		
		HttpServletRequest request = context.getRequest();
		HttpServletResponse response = context.getResponse();
		String encoding = context.getEncoding();
		Action action = context.getAction();
		
		InputStream inputStream = null;
		ServletOutputStream outputStream = null;
		DownloadInfo fileInfo = action.getDownloadInfo();
		
		//请求的前置处理方法
		if (!preDownload(request, response, fileInfo)) {
			//throw new AccessDeniedException("");
			response.sendError(HttpServletResponse.SC_NOT_FOUND, "file not found");
		}
		try {
			inputStream = action.getInputStream();
			outputStream = response.getOutputStream();
			
			int count;
			byte[] buffer = new byte[BUFFER_SIZE];
	        while ((count = inputStream.read(buffer)) > 0) {
	        	outputStream.write(buffer, 0, count);
	        }
		} catch (IOException e) {
			response.setContentType("text/html; charset=" + encoding);
			response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
		} finally {
			 try {
				outputStream.flush();
				outputStream.close();
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 前置下载处理
	 * 对HTTP的头信息进行处理
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @throws UnsupportedEncodingException 不支持指定的编码
	 */
	protected boolean preDownload(HttpServletRequest request, HttpServletResponse response, DownloadInfo fileInfo) throws UnsupportedEncodingException {
		
		//取得文件名
		String fileName = fileInfo.getFileName();
		//文件类型
		String contentType = fileInfo.getContentType();
		
		//文件名和文件类型不能为空
		if (StringUtils.isBlank(fileName) || StringUtils.isBlank(contentType)) {
			return false;
		}
		
    	String agent = (String) request.getHeader("USER-AGENT");  
    	if (agent != null && agent.indexOf("MSIE") > 0) {
    		fileName = java.net.URLEncoder.encode(fileName, fileInfo.getEncoding());
    	} else {
    		fileName = new String(fileName.getBytes(fileInfo.getEncoding()), "ISO-8859-1");
    	}
    	response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    	
		//设置响应头
		response.setCharacterEncoding(fileInfo.getEncoding());
    	response.setHeader("Content-Language", fileInfo.getEncoding());
    	response.setContentType(contentType);
    	response.setHeader("Pragma", "no-cache");
    	response.setHeader("cache-control", "no-cache");
    	response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
    	
    	return true;
	};
}
